package ua.exchangeratesukraine.actions;

import ua.exchangeratesukraine.R;
import ua.exchangeratesukraine.ui.fragment.SetDataListener;
import ua.exchangeratesukraine.util.Constants;
import ua.exchangeratesukraine.util.XmlParser;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

public class DataTask extends AsyncTask<String, Void, Object> {

	private Context	context	= null;
	private String	LOG_TAG	= getClass().getSimpleName();
	private WorkDB	workDB	= null;
	private String	state	= Constants.STATE_DEFAULT;

	DataTask() {
	}

	public DataTask(Context ctx, SetDataListener listener, WorkDB wdb) {
		context = ctx;
		setDataListener = listener;
		workDB = wdb;
	}

	private SetDataListener	setDataListener;
	@Override
	protected void onPreExecute() {
		super.onPreExecute();

		setDataListener.setProgressVisible();
	}

	@Override
	protected void onPostExecute(Object result) {
		super.onPostExecute(result);
		setDataListener.setProgressInVisible();
		setDataListener.setData(result, null, state);
	}

	@Override
	protected Object doInBackground(String... urls) {
		Log.d(LOG_TAG, "date : " + urls[1] + " | tableName : " + urls[2]);
		state = Constants.STATE_FROM_SERVER;
		return getResponseString(urls[1], urls[2], urls[0]);
	}

	private Object getResponseString(String date, String tableName, String url) {
		Object request = new NetRequest().getResponseString(context, url);
		// Log.d("DataTask", "response = " + object.toString());
		String connectionError = context.getString(R.string.text_toast_connection_error);
		String urlConnectionError = context.getString(R.string.text_toast_url_connection_error);
		if ((request.toString()).equals(connectionError)) {

			return connectionError;
		} else if ((request.toString()).equals(urlConnectionError)) {

			return urlConnectionError;
		} else if ((request.toString()).contains("requests_limit")) {

			return Constants.REQUESTS_LIMIT;
		} else {
			return XmlParser.parsingXml(new NetRequest().getResponseString(context, url));
		}
	}
}